#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include "Parser.hpp"
#include <ctime> 


int main() {
	const int RUN_TIMES = 1000;  // 1000000
	const std::string LOG_FILE_NAME = "./log/log_2.txt";
	const std::string CASE_PATH = "./case/";

	std::vector<std::string> cppNmaes = {
		"Q1-1.cpp",
		"Q1-2.cpp",
		"Q1-3.cpp",

		"Q2-1.cpp",
		"Q2-2.cpp",
		"Q2-3.cpp",

		"Q3-1.cpp",
		"Q3-2.cpp",
		"Q3-3.cpp",

		"my_case1.cpp",
		"my_case2.cpp",
		"my_case3.cpp"
	};

	std::vector<std::string> txtNames = {
		"Q1-1.txt",
		"Q1-2.txt",
		"Q1-3.txt",

		"Q2-1.txt",
		"Q2-2.txt",
		"Q2-3.txt",

		"Q3-1.txt",
		"Q3-2.txt",
		"Q3-3.txt",

		"my_case1.txt",
		"my_case2.txt",
		"my_case3.txt"
	};

	// 创建log文件
	std::ofstream outFile(LOG_FILE_NAME, std::ios::app);  //, std::ios::app
	if (!outFile.is_open()) {
		std::cerr << "Error: Could not open log file for writing!" << std::endl;
	}
	outFile.close();

	time_t startTime = time(nullptr);
	size_t caseSum = cppNmaes.size();
	int failedSum = 0;
	for (size_t codeId = 0; codeId < caseSum; ++codeId) {
		// 1.读取代码
		Parser parser(CASE_PATH + cppNmaes[codeId], CASE_PATH + txtNames[codeId]);
		bool code_got = parser.parse();
		if (!code_got) { 
			failedSum++;
			continue;
		}

		// 2.执行代码
		int times = 0;
		bool runSuccessed;
		while (times++ < RUN_TIMES) {
			runSuccessed = parser.evaluate();
		}
		if (!runSuccessed)failedSum++;

		// 3.打印结果，只打印一次
		const std::vector<std::string>& results = parser.get_results();
		outFile.open(LOG_FILE_NAME, std::ios::app);
		if (!outFile.is_open()) {
			std::cerr << "Error: Could not open file for writing!" << std::endl;
		}
		outFile << "case: " << codeId + 1 << "\n";		// 输出到文件
		//std::cout << "case: " << codeId + 1 << "\n";	// 输出到控制台
		size_t len = results.size();
		for (size_t i = 0; i < len; i++) {
			// 输出到文件
			outFile << "->imput: " << i + 1 << ":   \tgiven= " << parser.get_given_results()[i] << "  \tans= " << results[i] << "\n";
			// 输出到控制台
			//std::cout << "->imput: " << i + 1 << ":   \tgiven= " << parser.get_given_results()[i] << "  \tans= " << results[i] << "\n";
		}
		outFile.close();
		//std::cout << "\n";
	}

	time_t endTime = time(nullptr);
	time_t durationSeconds = endTime - startTime;
	std::cout << "Time taken:  " << durationSeconds << "  s" << std::endl;

	//std::ofstream outFile(LOG_FILE_NAME, std::ios::app);
	outFile.open(LOG_FILE_NAME, std::ios::app);
	if (!outFile.is_open()) {
		std::cerr << "Error: Could not open file for writing!" << std::endl;
	}
	outFile << "\nCase Sum:  " << caseSum << "\tFailed:  " << failedSum << "   \tIteration count:" << RUN_TIMES << "  \tTaken:  " << durationSeconds << " s" << std::endl;
	outFile << "===============================================================" << std::endl;
	outFile.close();


	return 0;
}

